home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 10628 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: druid.borland.com!usenet
  2. From: pete@borland.com (Pete Becker)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: rand ?
  5. Date: 19 Mar 1996 00:39:25 GMT
  6. Organization: Borland International
  7. Message-ID: <4ikvnt$nj6@druid.borland.com>
  8. References: <4idjt4$4du@itsop2.its.brooklyn.cuny.edu> <314BB352.2734@ccis.com>
  9. NNTP-Posting-Host: pbecker.borland.com
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=ISO-8859-1
  12. X-Newsreader: WinVN 0.99.5
  13.  
  14. In article <314BB352.2734@ccis.com>, wlund@ccis.com says...
  15. >
  16. >Daniel Zielinski wrote:
  17. >> 
  18. >> I need to generate random numbers between 0 and 51, I tried rand() with 
  19. srand(i)
  20. >> i changes constantly but the program never exits. looks like the random 
  21. number
  22. >> is always the same.  any help would be apriciated... thanss
  23. >> If you want a truely random number use something like this
  24. >
  25. >#define RANDOMIZE() srand(time(NULL)) /* time() is in time.h */
  26. >main()
  27. >{
  28. > int i ;
  29. > while(i != 0 )
  30. >  printf("%d\n",i = random(52));
  31. >}
  32. >
  33. > int random(int i)
  34. > {
  35. >  double x = RAND_MAX + 1.0 ;/* RAND_MAX is defined in stdlib.h */
  36. >  int y ; 
  37. >  RANDOMIZE();
  38.  
  39. There is rarely a need to call srand() more than once in any particular program 
  40. run. In addition, calling it from a tight loop like this will almost certainly 
  41. result in highly non-random results, because time() will return the same value 
  42. in several interations of the loop, resulting in the same value being returned 
  43. from the subsequent call to rand().
  44.  
  45. >  y = 1 + rand() * (i /x) ;
  46.  
  47. You didn't test this, did you? The program contains an infinite loop, since the 
  48. value of y, and therefore the return value of random, will never be 0.
  49.  
  50. >  return y ;
  51. > }
  52.  
  53.